<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.example.entity.Blog" %>
<%@ page import="org.example.DAO.BlogDAO" %>
<%@ page import="org.example.DAO.DBUtil" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.util.List" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.ArrayList" %>
<%@page import="java.net.URLEncoder"%>
<%
    System.out.println("[DEBUG] blog-list.jsp - userId: " + session.getAttribute("userId"));
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的日志 - 内容评级平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4cc9f0;
            --dark: #1d3557;
            --darker: #0d1b2a;
            --light: #f8f9fa;
            --gray: #8d99ae;
            --card-bg: rgba(29, 53, 87, 0.8);
            --transition: all 0.3s ease;
        }
        body {
            background: linear-gradient(135deg, var(--darker) 0%, var(--dark) 100%);
            color: var(--light);
            min-height: 100vh;
            background-attachment: fixed;
            line-height: 1.6;
            font-family: 'Inter', sans-serif;
        }
        .main-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 1rem;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }
        .section-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: var(--light);
            margin: 0;
        }
        .action-btn {
            background: var(--primary);
            color: var(--light);
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .action-btn:hover {
            background: var(--secondary);
            transform: translateY(-2px);
        }
        .btn-new {
            background: var(--accent);
            color: var(--darker);
        }
        .btn-new:hover {
            background: #36bff0;
        }
        .blog-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        .blog-card {
            background: var(--card-bg);
            backdrop-filter: blur(10px);
            border-radius: 0.5rem;
            padding: 1.5rem;
            transition: var(--transition);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
        }
        .blog-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
        }
        .blog-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 0.75rem;
            color: var(--light);
        }
        .blog-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            font-size: 0.875rem;
            color: var(--gray);
            margin-bottom: 1rem;
        }
        .blog-content {
            color: var(--light);
            margin-bottom: 1.5rem;
        }
        .blog-actions {
            display: flex;
            gap: 0.5rem;
        }
        .empty-state {
            text-align: center;
            padding: 3rem 0;
            color: var(--gray);
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--primary);
        }
        .empty-state h4 {
            font-size: 1.25rem;
            margin-bottom: 0.5rem;
        }
        .pagination {
            justify-content: center;
            margin-top: 2rem;
        }
        .page-link {
            background: var(--card-bg);
            color: var(--light);
            border: 1px solid var(--gray);
        }
        .page-link:hover {
            background: var(--primary);
            color: var(--light);
        }
        .page-item.active .page-link {
            background: var(--primary);
            border-color: var(--primary);
        }
    </style>
</head>
<body>
<jsp:include page="header.jsp" />
<div class="main-content">
    <div class="section-header">
        <h2 class="section-title">我的日志</h2>
        <a href="blog-edit.jsp" class="action-btn btn-new"><i class="fas fa-plus"></i> 写新日志</a>
    </div>
    <!-- 日志列表 -->
    <div class="blog-list">
        <%

            if (session == null || session.getAttribute("userId") == null) {
                // 确保重定向URL包含当前页面路径
                String redirectUrl = "blog-list.jsp";
                String queryString = request.getQueryString();
                if (queryString != null) {
                    redirectUrl += "?" + queryString;
                }

                // URL编码重定向参数
                String encodedRedirect = URLEncoder.encode(redirectUrl, "UTF-8");
                response.sendRedirect("Userlogin.jsp?redirect=" + encodedRedirect);
                return;
            }
            // 替换原有的复杂转换逻辑
            Integer userId = (Integer) session.getAttribute("userId");
            if(userId == null) {
                response.sendRedirect("Userlogin.jsp?redirect=blog-list.jsp");
                return;
            }
            // 未登录则重定向到登录页
            if (userId == null) {
                response.sendRedirect("Userlogin.jsp?redirect=blog-list.jsp"); // 关键修改：添加redirect参数
                return;
            }
            Connection conn = null;
            List<Blog> blogs = new ArrayList<>();
            String errorMessage = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                conn = DBUtil.getConnection();
                BlogDAO blogDAO = new BlogDAO(conn);
                blogs = blogDAO.getBlogsByUser(String.valueOf(userId));
            } catch (SQLException e) {
                e.printStackTrace();
                errorMessage = "获取日志列表失败，请稍后重试";
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 显示错误信息
            if (errorMessage != null) {
        %>
        <div class="empty-state">
            <i class="far fa-exclamation-triangle"></i>
            <h4>数据加载失败</h4>
            <p><%= errorMessage %></p>
        </div>
        <%
        }
        // 显示日志列表或空状态
        else if (blogs.isEmpty()) {
        %>
        <div class="empty-state">
            <i class="far fa-file-alt"></i>
            <h4>暂无日志</h4>
            <p>您还没有写过任何日志，点击右上角按钮开始创作吧</p>
        </div>
        <%
        } else {
            for (Blog blog : blogs) {
        %>
        <div class="blog-card">
            <h3 class="blog-title"><%= blog.getTitle() %></h3>
            <div class="blog-meta">
                <span><i class="far fa-calendar-alt"></i>
                    <%= blog.getCreatedAt() != null ? dateFormat.format(blog.getCreatedAt()) : "未知日期" %>
                </span>
                <span><i class="far fa-eye"></i>
                    <%= String.valueOf(blog.getViewCount()) %> 次浏览
                </span>
                <span><i class="far fa-comment"></i> 0 条评论</span>
                <span><i class="fas fa-thumbs-up"></i> 0 赞</span>
            </div>
            <div class="blog-content">
                <p><%= blog.getContent().length() > 100 ? blog.getContent().substring(0, 100) + "..." : blog.getContent() %></p>
            </div>
            <div class="blog-actions">
                <a href="blog-detail.jsp?id=<%= blog.getBlogId() %>" class="action-btn"><i class="far fa-eye"></i> 查看</a>
                <a href="blog-edit.jsp?blogId=<%= blog.getBlogId() %>" class="action-btn"><i class="far fa-edit"></i> 编辑</a>
                <a href="javascript:void(0)"
                   class="action-btn text-danger"
                   onclick="deleteBlog('<%= blog.getBlogId() %>')">
                    <i class="far fa-trash-alt"></i> 删除
                </a>
            </div>
        </div>
        <%
                }
            }
        %>
    </div>
    <!-- 分页 -->
    <nav aria-label="Page navigation">
        <ul class="pagination">
            <li class="page-item disabled">
                <a class="page-link" href="#" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <li class="page-item active"><a class="page-link" href="#">1</a></li>
            <li class="page-item"><a class="page-link" href="#">2</a></li>
            <li class="page-item">
                <a class="page-link" href="#" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>
</div>
<!-- 引入公共页脚 -->
<jsp:include page="footer.jsp" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 删除日志函数
    function deleteBlog(blogId) {
        // 防御性检查：若 blogId 为空，直接提示
        if (!blogId) {
            alert('错误：blogId 为空！请刷新页面重试');
            return;
        }

        if (confirm('确定要删除这篇日志吗？操作不可撤销！')) {
            $.ajax({
                url: '${pageContext.request.contextPath}/blog?blogId=' + blogId,
                type: 'DELETE',
                success: function (res) {
                    if (res.success) {
                        alert('删除成功！');
                        // 刷新列表（跳转到 blog-list 页面或重新请求数据）
                        window.location.href = 'blog-list.jsp';
                    } else {
                        alert('删除失败：' + res.message);
                    }
                },
                error: function () {
                    alert('网络错误！请检查请求地址');
                }
            });
        }
    }
</script>

</body>
</html>